package com.kungfuhacking.wristbandpro.my;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSONObject;
import com.kungfuhacking.wristbandpro.R;
import com.kungfuhacking.wristbandpro.base.Mapplication;
import com.kungfuhacking.wristbandpro.base.bean.Basebean;
import com.kungfuhacking.wristbandpro.base.bean.RequestBean;
import com.kungfuhacking.wristbandpro.base.view.BaseFragment;
import com.kungfuhacking.wristbandpro.location.bean.OldEntity;
import com.kungfuhacking.wristbandpro.login.activity.LoginActivity;
import com.kungfuhacking.wristbandpro.mqtt.MqttConstant;
import com.kungfuhacking.wristbandpro.mqtt.MqttManager;
import com.kungfuhacking.wristbandpro.my.activity.OldDetailActivity;
import com.kungfuhacking.wristbandpro.my.presenter.FamilyAdapter;
import com.kungfuhacking.wristbandpro.my.presenter.IFamilyPresenter;
import com.kungfuhacking.wristbandpro.my.view.IFamilyView;
import com.kungfuhacking.wristbandpro.net.BaseNoTObserver;
import com.kungfuhacking.wristbandpro.net.RetrofitHttpUtil;
import com.kungfuhacking.wristbandpro.utils.CommonUtils;
import com.kungfuhacking.wristbandpro.utils.Constant;
import com.kungfuhacking.wristbandpro.widget.swipe.DividerItemDecoration;
import com.kungfuhacking.wristbandpro.widget.swipe.OnItemClickListener;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import io.reactivex.disposables.Disposable;
import mqttresource.MqttException;

/**
 * 我的页面
 * Created by Aaron on 17/4/18.
 */

public class FragmentMy extends BaseFragment implements IFamilyView, SwipeRefreshLayout.OnRefreshListener {

    private IFamilyPresenter iFamilyPresenter = new IFamilyPresenter(this);
    //    private SimpleDraweeView sdvhead;
//    private android.widget.TextView tvname;
    private String TAG = getClass().getSimpleName();
    private Mapplication mApplication;
    private RecyclerView recycleView;
    private List<OldEntity> oldEntities = new ArrayList<>();
    private FamilyAdapter familyAdapter;
    //    private ImageView tv_notice;
//    private boolean is_notice;
    private SwipeRefreshLayout swipeRefreshLayout;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View myView = View.inflate(getActivity(), R.layout.fragment_my, null);

        mApplication = (Mapplication) getActivity().getApplication();
        initWidget(myView);
        return myView;
    }

    @Override
    public void onResume() {
        super.onResume();
        iFamilyPresenter.familyInfo();
    }

    private void initWidget(View view) {

        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeRefreshLayout);
        //为SwipeRefreshLayout设置监听事件
        swipeRefreshLayout.setOnRefreshListener(this);
//        //为SwipeRefreshLayout设置刷新时的颜色变化，最多可以设置4种
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        recycleView = (RecyclerView) view.findViewById(R.id.recycleView);

        initRecycleView();
    }

    private void initRecycleView() {
        recycleView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recycleView.setItemAnimator(new DefaultItemAnimator());
        familyAdapter = new FamilyAdapter(getActivity(), oldEntities, this);
        recycleView.setAdapter(familyAdapter);
        recycleView.addItemDecoration(new DividerItemDecoration(getActivity(),
                DividerItemDecoration.VERTICAL_LIST,
                getResources().getDrawable(R.color.bg_gray)));
        recycleView.addOnItemTouchListener(new OnItemClickListener(recycleView) {
            @Override
            public void onItemClick(RecyclerView.ViewHolder holder, int position) {

                if (position == 0 || position > oldEntities.size()) {
                    return;
                }

                --position;
                Intent mIntent = new Intent(getActivity(), OldDetailActivity.class);
                if (oldEntities != null) {
                    mIntent.putExtra("id", oldEntities.get(position).getId());
                    mIntent.putExtra("level", oldEntities.get(position).getLevel());
                }
                startActivity(mIntent);
            }

            @Override
            public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

            }
        });

    }

    /**
     * 0 false 不通知
     * 1 true 通知
     *
     * @param isNotice
     */
    public void updatePushStatus(final boolean isNotice) {
        JSONObject j = new JSONObject();
        j.put("token", getToken());
        j.put("isPush", isNotice ? "0" : "1");

        RetrofitHttpUtil.getInstance().updateUserPushState(new BaseNoTObserver<Basebean>() {
            @Override
            public void onHandleSuccess(Basebean basebean) {
//                tv_notice.setSelected(!is_notice);
                sp.edit().putBoolean(Constant.IS_NOTICE, !isNotice).apply();
                familyAdapter.notifyDataSetChanged();
//                is_notice = !is_notice;
            }

            @Override
            public void onHandleError(String message) {
                showErr(message);
            }

            @Override
            public void onReLogin(String message) {
                showErr(message);
                nextActivityWithSingleTask(LoginActivity.class);
            }

            @Override
            public void onSubscribe(Disposable d) {

            }
        }, new RequestBean().setData(j.toString()));
    }


    //退出
    public void quit() {

        new AlertDialog.Builder(getActivity()).setTitle("提示")
                .setMessage("确定要退出吗?")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                Set<String> remaindSet = sp.getStringSet(MqttConstant.REMAIND + sp.getString(MqttConstant.USERID, ""), new LinkedHashSet<String>());
                String userId = sp.getString(MqttConstant.USERID, "");

                //删除用户的数据信息
                sp.edit().clear().apply();
                //保存 消息不提醒的topic至文件中
//                Log.d(TAG, "保存的不要提醒的消息" + remaindSet.toString());
                CommonUtils.fileSave(MqttConstant.REMAIND + userId, remaindSet);

                dialog.dismiss();

                try {

                    if (MqttManager.getInstance().getMqttClient() != null && MqttManager.getInstance().getMqttClient().isConnected())
                        MqttManager.getInstance().getMqttClient().disconnect();
                } catch (MqttException e) {
                    e.printStackTrace();
//                    showErr("退出失败");
                }

                //退出mqtt
                try {
                    mApplication.exitMqtt();
                } catch (MqttException e) {
                    e.printStackTrace();
                }

                Intent intent = new Intent(getActivity(), LoginActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                intent.putExtra("exit", true);
                startActivity(intent);

            }
        }).show();

    }

    @Override
    public void onRefresh() {
        oldEntities.clear();
        familyAdapter.setOldEntities(oldEntities);
        familyAdapter.notifyDataSetChanged();
        iFamilyPresenter.familyInfo();
        //结束后停止刷新
        swipeRefreshLayout.setRefreshing(false);
    }

    @Override
    public void setAdapterData(List<OldEntity> oldEntities) {

        this.oldEntities = oldEntities;
        familyAdapter.setOldEntities(oldEntities);
        familyAdapter.notifyDataSetChanged();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        iFamilyPresenter.clearRequest();
    }

    public void exChangeNotice(final boolean isNotice) {
        if (isNotice) {
            //如果当前是通知状态，则提示

            new AlertDialog.Builder(getActivity()).setTitle("提示").setMessage("关闭后您将无法收到消息推送")
                    .setNegativeButton("取消关闭", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).setPositiveButton("继续关闭", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    updatePushStatus(isNotice);
                }
            }).show();
        } else
            updatePushStatus(isNotice);
    }
}
